<template>
  <Spin :spinning="loading" tip="Loading...">
  <div>
    <!-- table -->
    <!-- 紧急返件要求下发 - 新增 -->
    <BreakSpace label="质量信息" :containerStyle="{ marginBottom: '10px' }"/>
    <FormPanel ref="formPanel1" :list="formList" :cols="3" :formType="'add'" labelWidth="110" :isSubmitBtn="false"
               @formChange="formChangeHandle"/>
    <div style="margin-bottom: 1rem;"></div>
    <BreakSpace label="紧急返件列表" :containerStyle="{ marginBottom: '10px' }" />
    <FilterTable
      ref="table"
      :columns="columns"
      :params="fetchParams"
      :dataSource="dataList"
      :datakey="'items'"
      :onColumnsChange="columns => (this.columns = columns)"
      :onRowSelectChange="selectChange"
      selectionType="single"
      height="auto"
    > <template slot="controls" slot-scope="props">
    </template></FilterTable>
    <div style="margin-bottom: 1rem;"></div>
    <FormPanel ref="formPanel2" :list="formList2" :cols="3" :formType="'add'" labelWidth="100" :isSubmitBtn="false"
               @formChange="form2ChangeHandle"/>
    <div style="margin-bottom: 3rem;"></div>
    <div
      :style="{
        position: 'fixed',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right'
      }"
    >
      <multiuse-button type="primary" :click="reject.bind(this)">驳回</multiuse-button>
      <multiuse-button type="primary" :click="saveDialog.bind(this)">通过</multiuse-button>
      <multiuse-button type="primary" @click="closeDialog">关 闭</multiuse-button>
    </div>
    <BaseDialog :visible.sync="quality" :title="'车型选择'" destroyOnClose width="850px" :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}">
      <quality @close="close" @save="saveQuality"></quality>
    </BaseDialog>
    <BaseDialog :visible.sync="zhusunjian" :title="'主损件选择'" destroyOnClose :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}">
      <Selectzhusunjian @close="zhusunjianClose" @save="zhusunjianSave"></Selectzhusunjian>
    </BaseDialog>
    <BaseDialog :visible.sync="showImport" title="导入" icon="el-icon-upload" width="800px" destroyOnClose :containerStyle="{ height: '100%', overflow: 'auto'  }">
      <importPeiJianLeiXingWeiHu @importclose="editsave()" />
    </BaseDialog>
    <div style="margin-bottom: 1rem;"></div>
  </div>
  </Spin>
</template>
<script>
  import quality from './qualityNoQuery.vue';
  import { getPartType } from '@/api/dictionary/index';
  import Selectzhusunjian from '@/pages/claimDemage/tools/vehicle.vue';
  import {editSave,approveByPtId,quyUrgent} from '@/api/claim/factory/QualityInformationManagement_OEM/CoreIssueRules';
  import { isFormEmpty } from '@/utils/index';
  import { copyUpdateData } from '@/utils/index';
  import { dictionary } from '@/utils/dictMixin';
  export default {
    props: ['type', 'rowData'],
    mixins: [dictionary],
    components: {
      quality,Selectzhusunjian

    },
    data() {
      return {
        loading: false,
        dataList: [],
        collapse: false,
        infoId: null,
        // topFilterInit: this.topFilterInitFun(),
        // fetchApi: getUser,
        fetchParams: {}, //ipa 接口
        selectedRows: [], //选中经销商
        columns: this.creatHeader(),
        formList: this.createFormList(),
        formList2: this.createFormList2(),
        saveData: null,
        saveData1:null,
        quality:false,
        zhusunjian:false,
        showImport:false,
      };
    },
    async created() {
      this.loading = true;
      await this.chuqi();
      await this.getList(this.rowData.urgentId);
      this.loading = false;
    },
    methods: {
      async chuqi() {
        // console.log("进来了")
        // const res1 = await getPartType({type: 5564});
        // if (res1.resultCode == 200) {
        //   this.formList.find(x => x.fieldName == 'dataSource').itemList = res1.data.map(y => ({
        //     text: y.codeCnDesc,
        //     value: y.codeId
        //   }));
        // }
        // const res2 = await getPartType({type: 5565});
        // if (res1.resultCode == 200) {
        //   this.formList.find(x => x.fieldName == 'urgentStatus').itemList = res2.data.map(y => ({
        //     text: y.codeCnDesc,
        //     value: y.codeId
        //   }));
        // }
      },
      async getList(id) {
        let res = await quyUrgent({ id: id });
        let data = res.data;
        //临时属性
        this.partId = data.partId; //主损件id
        this.modelId = data.modelId; //车型id
        this.modelCode = data.modelCode; //车型Code
        this.reportId = data.reportId; //故障现象主键
        this.cmsClaimId = data.cmsClaimId;

        //为2个form赋值
        for (let i in data) {
          this.formList.map(y => {
            if (i == y.fieldName) {
              y.initialValue = data[i];
            }
          });
        }

        for (let i in data) {
          this.formList2.map(y => {
            if (i == y.fieldName) {
              y.initialValue = data[i];
            }
          });
        }
        //为table赋值

        let records2 = data.dtlList;
        if (isFormEmpty(records2)) {
          records2 = [];
        }
        let partIds = [];
        this.$refs.table.$refs.pageTable.EXECUTE_INSERT(records2);
        this.$refs.table.$refs.pageTable.list.map(x => {
          partIds.push(x.dtlId);
        });
        let ids = '';
        partIds.map(x => {
          ids += x + ','
        });
        this.partIds = ids;
        console.info(res);
        this.newVar = data;
      },
      editsave() {
        this.showImport = false;
        this.fetchParams = { ...this.fetchParams };
      },
      showImportFun() {
        this.showImport = true;
      },
      qualityNo() {
        this.quality = true;
      },
      formChangeHandle(val) {
        console.log(val);
        this.saveData = val;
      },
      form2ChangeHandle(val) {
        console.log(val);
        this.saveData1 = val;
      },
      //搜索获取数据
      changeHandle(val) {
        this.fetchParams = val;
        console.log(val);
      },
      //选中
      selectChange(rows) {
        this.selectedRows = rows;
        console.log(this.selectedRows);
      },
      async reject(){
        this.$refs.formPanel1.SUBMIT_FORM();
        this.$refs.formPanel2.SUBMIT_FORM();
        this.saveData = Object.assign(this.saveData, this.saveData1);

        let arr2 = [];
        this.$refs.table.$refs.pageTable.list.map(x => {
          delete  x.dtlId;
          arr2.push(x);
        });
        this.saveData.dtlList = arr2;
        this.saveData.reportId = this.reportId;
        this.saveData.cmsClaimId = this.cmsClaimId;
        this.saveData.delDtlIds = this.partIds;
        this.saveData.urgentId = this.rowData.urgentId;
        this.saveData.ownerCode = this.rowData.ownerCode;
        this.saveData.isDeleted = this.rowData.isDeleted;
        this.saveData.urgentStatus = 55651004;
        this.newVar = copyUpdateData(this.newVar,this.saveData);
        this.loading = true;
          let res = await approveByPtId(this.newVar);
          if (res.resultCode === 200) {
            this.closeDialog('refresh');
            return this.$notify.success({ title: '提示信息', message: '保存成功' });
            this.$emit('save');
          } else {
            this.loading = false;
            this.$notify.error({ title: '提示信息', message: res.errMsg || '保存失败!' });
            this.closeDialog();
          }

      },
      //保存
      async saveDialog() {
        this.$refs.formPanel1.SUBMIT_FORM();
        this.$refs.formPanel2.SUBMIT_FORM();
        this.saveData = Object.assign(this.saveData, this.saveData1);

        let arr2 = [];
        this.$refs.table.$refs.pageTable.list.map(x => {
          delete  x.dtlId;
          arr2.push(x);
        });
        this.saveData.dtlList = arr2;
        this.saveData.urgentStatus = 55651003;
        this.saveData.reportId = this.reportId;
        this.saveData.cmsClaimId = this.cmsClaimId;
        this.saveData.delDtlIds = this.partIds;
        this.saveData.urgentId = this.rowData.urgentId;
        this.saveData.ownerCode = this.rowData.ownerCode;
        this.saveData.isDeleted = this.rowData.isDeleted;
        this.newVar = copyUpdateData(this.newVar,this.saveData);
        this.loading = true;
        let res = await approveByPtId(this.newVar);
        if (res.resultCode === 200) {
          this.$emit('save');
          return this.$notify.success({ title: '提示信息', message: '保存成功' });
        } else {
          this.loading = false;
          this.$notify.error({ title: '提示信息', message: res.errMsg || '保存失败!' });
          this.closeDialog();
        }

      },
      zhusunjianSave(obj) {
        let falg = true ;

        this.$refs.table.$refs.pageTable.list.map(x => {
          if(obj[0].partCode == x.partCode){
            falg = false;
            this.$notify.error({ title: '提示信息', message: '配件选择重复' });
          }
        });
        if(falg){
          this.$refs.table.$refs.pageTable.EXECUTE_INSERT(obj);
        }
        this.zhusunjian = false;
      },
      //主损件
      zhusunjianClose() {
        this.zhusunjian = false;
      },
      //取消操作
      closeDialog() {
        this.$emit('close', {visible: false, data: this.selectedRows, type: 'close'});
      },
      addTurnOn(){
        this.zhusunjian = true;
      },
      close(){
        this.quality = false;
      },
      saveQuality(obj) {
        this.formList.find(x => x.fieldName == 'reportNo').initialValue = obj[0].reportNo;
        this.formList.find(x => x.fieldName == 'dealerCode').initialValue = obj[0].ownerCode;
        this.formList.find(x => x.fieldName == 'dealerName').initialValue = obj[0].dealerName;
        this.formList.find(x => x.fieldName == 'roNo').initialValue = obj[0].roNo;
        this.formList.find(x => x.fieldName == 'vin').initialValue = obj[0].vin;
        this.formList.find(x => x.fieldName == 'cmsClaimNo').initialValue = obj[0].cmsClaimNo;
        this.formList.find(x => x.fieldName == 'prodDate').initialValue = obj[0].prodDate;
        this.formList.find(x => x.fieldName == 'saleDate').initialValue = obj[0].saleDate;
        this.formList.find(x => x.fieldName == 'driveMile').initialValue = obj[0].driveMile;
        this.formList.find(x => x.fieldName == 'serviceBeginDate').initialValue = obj[0].serviceBeginDate;
        this.formList.find(x => x.fieldName == 'partCode').initialValue = obj[0].partCode;
        this.formList.find(x => x.fieldName == 'partName').initialValue = obj[0].partName;
        this.formList.find(x => x.fieldName == 'serviceEndDate').initialValue = obj[0].serviceEndDate;
        this.formList.find(x => x.fieldName == 'faultCode').initialValue = obj[0].faultCode;
        this.formList.find(x => x.fieldName == 'faultName').initialValue = obj[0].faultName;
        this.formList.find(x => x.fieldName == 'modelName').initialValue = obj[0].modelName;
        this.cmsClaimId = obj[0].cmsClaimId;
        this.reportId = obj[0].reportId;
        this.quality = false;
      },
      delsFunXj(data) {
        this.$refs.table.$refs.pageTable.EXECUTE_DELETE([data]);
      },
      //基本信息
      createFormList() {
        return [
          {
            type: 'INPUT',
            label: '紧急返件单号',
            fieldName: 'urgentNo',
            readonly: true,// 只读
            disabled: true // 置会
          },
          {
            type: 'INPUT',
            label: '质量报告单号',
            fieldName: 'reportNo',
            readonly: true,// 只读
            disabled: true // 置会
          },
          {
            type: 'SELECT',
            label: '数据来源',
            fieldName: 'dataSource',
            readonly: true,// 只读
            disabled: true, // 置会
            itemList: this.createDictList('5564'),
          },
          {
            type: 'INPUT',
            label: '经销商代码',
            fieldName: 'dealerCode',
            readonly: true,// 只读
            disabled: true // 置会
          },
          {
            type: 'INPUT',
            label: '经销商名称',
            fieldName: 'dealerName',
            readonly: true,// 只读
            disabled: true // 置会
          },
          {
            type: 'SELECT',
            label: '紧急返件单状态',
            fieldName: 'urgentStatus',
            readonly: true,// 只读
            disabled: true, // 置会
            itemList: this.createDictList('5565'),
          },
          {
            type: 'INPUT',
            label: '索赔单号',
            fieldName: 'cmsClaimNo',
            readonly: true,// 只读
            disabled: true // 置会
          },
          {
            type: 'INPUT',
            label: 'VIN',
            fieldName: 'vin',
            readonly: true,// 只读
            disabled: true // 置会
          },
          {
            type: 'INPUT',
            label: '车型名称',
            fieldName: 'modelName',
            readonly: true,// 只读
            disabled: true // 置会
          }
        ];
      },
      creatHeader() {
        return [
          {
            title: '序号',
            dataIndex: 'index',
            width: 80,
            sorter: true,
            render: props => {
              return <span>{props.row.index + 1}</span>;
            }
          },
          { title: '配件代码', dataIndex: 'partCode', sorter: true },
          { title: '配件名称', dataIndex: 'partName', sorter: true },
          { title: '单位', dataIndex: 'partUnit', sorter: true },
          { title: '数量', dataIndex: 'partCount', sorter: true },
          {
            title: '收件人',
            dataIndex: 'receiver',
            sorter: true,
          }, {
            title: '收件人电话',
            dataIndex: 'receiverTel',
            sorter: true,
          }, {
            title: '收件地址',
            dataIndex: 'receiverAddress',
            sorter: true,
          },

        ];
      },
      createFormList2() {
        return [
          {
            type: 'INPUT',
            label: '返件要求说明',
            fieldName: 'urgentRemarks',
            selfCols: 3,// 元素占据几行
            rows: 2,
            disabled:true,
          }
        ];
      },
    }
  };
</script>

<style lang="less" scoped></style>
